package com.yunhe.realtime.controller.data;

import com.yunhe.common.constant.CacheConsts;
import com.yunhe.common.constant.KafkaConsts;
import com.yunhe.common.exception.ObjectNotFoundException;
import com.yunhe.common.model.ResultObject;
import com.yunhe.realtime.service.data.RealtimeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.Optional;

/**
 * 自定义实时数据Controller
 * @author liuronglei
 * @version 2.3.1
 */
@Api(value = "realtime_custom",description = "自定义实时数据", tags = {"Data_CustomRealtime"})
@RestController
@EnableAsync
@RequestMapping("/measurements/realtime/custom")
public class CustomController {
    private static Logger logger = LoggerFactory.getLogger(CustomController.class);
    @Autowired
    private RealtimeService realtimeService;

    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;

    /**
     * 根据key获得实时值
     */
    @ApiOperation("根据key获得实时值")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "key", value = "redis中的键", required = true, dataType = "string", paramType = "query")
    })
    @RequestMapping(method = RequestMethod.GET)
    public ResponseEntity<ResultObject> getCustomRealtime(@RequestParam("key") String key)
            throws ObjectNotFoundException {
        Map result = realtimeService.getMap(CacheConsts.KEY.CUSTOM_REALTIME.value(key));
        return new ResponseEntity<>(new ResultObject<>(result), HttpStatus.OK);
    }

    /**
     * 设置实时值
     * @param key redis中的键
     * @param value 值
     */
    @ApiOperation("设置实时值")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "key", value = "redis中的键", required = true, dataType = "string", paramType = "query")
    })
    @RequestMapping(method = RequestMethod.POST)
    public ResponseEntity<ResultObject> saveCustomRealtime(@RequestParam("key") String key,
                                                           @RequestBody Map value) {
        realtimeService.setMap(CacheConsts.KEY.CUSTOM_REALTIME.value(key), value, Optional.of(CacheConsts.LIVE_TIME.MINUTE_5.value()));
        kafkaTemplate.send(KafkaConsts.Topic.CustomRealtime, key);
        return new ResponseEntity<>(new ResultObject<>(null), HttpStatus.OK);
    }
}